package org.surelink.radius.middleware.auth;


import org.surelink.radius.cache.GroupCache;
import org.surelink.radius.cache.UserCache;
import org.surelink.radius.middleware.AuthMiddleware;
import org.surelink.radius.model.User;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.tinyradius.dictionary.AttributeType;
import org.tinyradius.dictionary.DefaultDictionary;
import org.tinyradius.packet.AccessRequest;
import org.tinyradius.packet.RadiusPacket;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class AttributeMiddleware implements AuthMiddleware
{

    private static final Logger log = Logger.getLogger(AttributeMiddleware.class);

    @Autowired
    private UserCache userCache;

    @Autowired
    private GroupCache groupCache;

    @Override
    public RadiusPacket onAuth(User user, AccessRequest request, RadiusPacket response) throws Exception {
        if(log.isInfoEnabled())
            log.info("start AttributeMiddleware ...");

        Map<String,String> userMeta = userCache.getUserMetas(user.getUserName());
        Map<String,String> groupMeta = groupCache.getGroupMetas(user.getGroupName());


        Map<String, String> metasMap = new HashMap<String, String>();

        if (groupMeta != null) {
            for (Map.Entry<String,String> radGroupMeta : groupMeta.entrySet()) {
                metasMap.put(radGroupMeta.getKey(), radGroupMeta.getValue());
            }
        }

        if (userMeta != null) {
            for (Map.Entry<String,String> radUserMeta : userMeta.entrySet()) {
                metasMap.put(radUserMeta.getKey(), radUserMeta.getValue());
            }
        }

        for (Iterator<Map.Entry<String, String>> iterator = metasMap.entrySet().iterator(); iterator.hasNext();) {
            Map.Entry<String, String> ent = iterator.next();

            AttributeType attrType = DefaultDictionary.getDefaultDictionary().getAttributeTypeByName(ent.getKey());
            if (attrType != null) {
                response.removeAttributes(attrType.getTypeCode());
                response.addAttribute(ent.getKey().trim(), ent.getValue());
            }
        }

        return response;
    }
}
